package function

import (
	"reflect"

	"gitee.com/knowgo/ego/core/data"
	"gitee.com/knowgo/ego/core/inject"
	"gitee.com/knowgo/ego/egoc"
)

type InjectArg struct {
	injector *inject.Injector
	// isPtr 是否指针
	isPtr bool
}

func NewInjectArg(injector *inject.Injector, isPtr bool) *InjectArg {
	return &InjectArg{injector: injector, isPtr: isPtr}
}

func (s *InjectArg) Value(request *data.ServiceRequest, ctx *egoc.Context, argCtx *ArgContext) (reflect.Value, error) {
	v, ok := argCtx.InjectValueMap[s.injector.Type]
	if !ok {
		val, err := s.injector.Create(ctx)
		v = &InjectValue{Value: val, Err: err}
		argCtx.InjectValueMap[s.injector.Type] = v
	}
	if s.isPtr {
		return v.Value, v.Err
	}
	return v.Value.Elem(), v.Err
}
